/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.agenda.model.persistence;

import com.agenda.model.entity.AmTbMedi;
import com.agenda.model.repository.MedicoRepository;
import java.util.List;
import javax.persistence.Query;

/**
 *
 * @author ronildo
 */
public class MedicoDAO extends GenericDAO<AmTbMedi, MedicoRepository> implements MedicoRepository {
    
    public AmTbMedi findById(Long id) {
        return (AmTbMedi)em.createNamedQuery("AmTbMedi.findByCdMedi").
                setParameter("cdMedi", id).getSingleResult();
        
    }

    public List<AmTbMedi> list(AmTbMedi amTbMedi){
        try{
            
            String hql = "select medico from AmTbMedi as medico ";
            hql+=" where medico.cdMedi = medico.cdMedi";
            
            if(amTbMedi.getNmMedi() != null && amTbMedi.getNmMedi().equals(""))
                    hql+=" and medico.nmMedi like :nmMedi";
            if(amTbMedi.getNrCpf() > 0)
                    hql+=" and medico.nrCpf = :nrCpf";
            if(amTbMedi.getNrCrm() > 0)
                    hql+=" and medico.nrCrm = :nrCrm";
            if(amTbMedi.getDtNasc() != null)
                    hql+=" and medico.dtNasc = :dtNasc";
            if(amTbMedi.getDtCada() != null)
                    hql+=" and medico.dtCada = :dtCada";
            hql+=" order by medico.cdMedi";

            Query query = em.createQuery(hql);
            if(amTbMedi.getNmMedi() != null && amTbMedi.getNmMedi().equals(""))
                query.setParameter("nmMedico", "%"+amTbMedi.getNmMedi()+"%");
            if(amTbMedi.getNrCpf() > 0)
                query.setParameter("nrCpf", amTbMedi.getNrCpf());
            if(amTbMedi.getNrCrm() > 0)
                query.setParameter("nrCrm", amTbMedi.getNrCrm());
            if(amTbMedi.getDtNasc() != null)
                query.setParameter("dtNasc", amTbMedi.getDtNasc());
            if(amTbMedi.getDtCada() != null)
                query.setParameter("dtCada", amTbMedi.getDtCada());
            
            return query.getResultList();
        }catch(RuntimeException e){
            throw new DAOException(e);
        }
    }

    public List<AmTbMedi> listAll(){
        try{
            return em.createNamedQuery("AmTbMedi.findAll").getResultList();
        }catch(IllegalStateException e){
            throw new DAOException(e);
        }
    }
}
